package org.example.demo7.web;

/**
 * @author zyp
 * @version 1.0
 */

import com.google.gson.Gson;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet("/ChatServlet")
public class ChatServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    // 存储聊天消息的列表，作为所有用户共享的数据
    private Map<Long, Message> chatMessages = new HashMap<>();
    private long nextMessageId = 1;
    private ServletContext context;
    static class Message {
        String sender;
        String message;
        String receiver;

        public Message(String sender, String message, String receiver) {
            this.sender = sender;
            this.message = message;
            this.receiver = receiver;
        }

        @Override
        public String toString() {
            if (receiver == null) {
                return sender + ": " + message;
            } else {
                return sender + " -> " + receiver + ": " + message;
            }
        }
    }
    @Override
    public void init() throws ServletException {
        context = getServletContext();
        // 初始化在线用户列表
        List<String> onlineUsers = getOnlineUsers();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("getOnlineUsers".equals(action)) {
            // 返回在线用户列表
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            List<String> onlineUsers = getOnlineUsers();
            PrintWriter writer = response.getWriter();
            writer.write(new Gson().toJson(onlineUsers));
            writer.flush();
        }  else if ("getMessages".equals(action)) {
            // 返回聊天消息
            response.setContentType("text/event-stream");
            response.setCharacterEncoding("UTF-8");
            String lastMessageIdStr = request.getParameter("lastMessageId");
            long lastMessageId = lastMessageIdStr == null ? 0 : Long.parseLong(lastMessageIdStr);
            String currentUserName = (String) request.getSession().getAttribute("userName");

            PrintWriter writer = response.getWriter();

            for (Map.Entry<Long, Message> entry : chatMessages.entrySet()) {
                if (entry.getKey() > lastMessageId) {
                    Message message = entry.getValue();
                    if (isMessageForUser(message, currentUserName)) {
                        writer.write("id: " + entry.getKey() + "\n");
                        writer.write("data: " + message.toString() + "\n\n");
                    }
                }
            }
            writer.flush();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String sender = request.getParameter("sender");
        String messageText = request.getParameter("message");
        String receiver = request.getParameter("receiver");

        if (sender != null && messageText != null && receiver != null) {
            if (receiver.equals("all")) {
                // 群聊
                Message message = new Message(sender, messageText, null);
                chatMessages.put(nextMessageId++, message);
            } else {
                // 私聊
                Message message = new Message(sender, messageText, receiver);
                chatMessages.put(nextMessageId++, message);
            }
        }
    }

    private boolean isMessageForUser(Message message, String currentUserName) {
        if (message.receiver == null) {
            // 群聊消息
            return true;
        } else {
            // 私聊消息
            return message.sender.equals(currentUserName) || message.receiver.equals(currentUserName);
        }
    }
    // 方法用于获取在线用户列表
    public List<String> getOnlineUsers() {
        List<String> onlineUsers = (List<String>) context.getAttribute("onlineUsers");
        if (onlineUsers == null) {
            onlineUsers = new ArrayList<>();
            context.setAttribute("onlineUsers", onlineUsers);
        }
        return onlineUsers;
    }

    // 方法用于添加在线用户
    public void addOnlineUser(String userName) {
        List<String> onlineUsers = getOnlineUsers();
        // 将用户添加到在线用户列表
        if (!onlineUsers.contains(userName)) {
            onlineUsers.add(userName);
            System.out.println("User " + userName + " has logged in and added to the online users list.");
        }
    }

    // 方法用于移除离线用户
    public void removeOfflineUser(String userName) {
        List<String> onlineUsers = getOnlineUsers();
        onlineUsers.remove(userName);
    }
}